package com.beiing.tianshuai.tianshuai.activity;

import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;

public class CommonWebViewActivity extends BaseActivity {
    private ProgressBar mLoadingProgress;
    private WebView webView;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_common_web_view;
    }

    @Override
    protected void init() {
        webView = (WebView) findViewById(R.id.wv_common_web_view);
        mLoadingProgress = (ProgressBar) findViewById(R.id.progress_bar_loading);
        TextView tvTitle = (TextView) findViewById(R.id.toolbar_tv_title);
        ImageView back = (ImageView) findViewById(R.id.toolbar_iv_back);

        back.setVisibility(View.VISIBLE);
        Intent intent = getIntent();
        String url = intent.getStringExtra("url");
        String title = intent.getStringExtra("title");
        tvTitle.setText(title);
        mLoadingProgress.setMax(100);

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        webView.loadUrl(url);
        webView.setWebChromeClient(new WebChromeClientProgress());

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private class WebChromeClientProgress extends WebChromeClient{
        @Override
        public void onProgressChanged(WebView view, int progress) {
            if (mLoadingProgress != null) {
                mLoadingProgress.setProgress(progress);
                if (progress == 100) mLoadingProgress.setVisibility(View.GONE);
            }
            super.onProgressChanged(view, progress);
        }
    }

    /**
     * 按键响应，在WebView中查看网页时，检查是否有可以前进的历史记录。
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack())
        {

            // 返回键退回
            webView.goBack();
            return true;
        }
        // If it wasn't the Back key or there's no web page history, bubble up
        // to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }
}
